import { DataSource, EntityManager } from 'typeorm';
import { SpiderTask, SpiderSubTask, SpiderTaskStatus, SpiderTaskType } from './task'
let ds: DataSource;

export interface EntityManagerHandler<T> {
    (m: EntityManager): Promise<T>;
}

export async function useEntityManager<T = any>(h: EntityManagerHandler<T>) {
    const ds = await useDataSource()
    const m = ds.createEntityManager()
    return m.transaction(h)
}

export async function useDataSource() {
    if (ds) {
        if (ds.isInitialized) return ds;
        await ds.initialize()
        return ds;
    }
    const url = process.env.DATABASE_URL
    ds = new DataSource({
        type: 'postgres',
        url: url,
        entities: [
            SpiderTask,
            SpiderSubTask
        ],
        synchronize: process.env.NODE_ENV === 'development'
    })
    await ds.initialize()
    return ds;
}

export {
    SpiderTask,
    SpiderSubTask,
    SpiderTaskStatus, 
    SpiderTaskType
}